package gui;

import io.Cliente;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import logica.Verificador;
import logica.VerificadorException;

/**
 *
 * @author Mariano Zapata
 */
public class DialogoCrearCliente extends javax.swing.JPanel {

    private Cliente retorno;
    
    /** Creates new form DialogoCrearCliente */
    public DialogoCrearCliente()
    {
        initComponents();
        Image icono= new ImageIcon(getClass().getResource("/gui/icono/logo_chico.png")).getImage();
        dialogo.setIconImage(icono);
        dialogo.getContentPane().setLayout(new BorderLayout());
        retorno= null;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dialogo = new javax.swing.JDialog();
        jLabel1 = new javax.swing.JLabel();
        apellido = new javax.swing.JTextField();
        nombres = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        crear = new javax.swing.JButton();

        dialogo.setTitle("Crear cliente");
        dialogo.setModal(true);
        dialogo.setResizable(false);

        javax.swing.GroupLayout dialogoLayout = new javax.swing.GroupLayout(dialogo.getContentPane());
        dialogo.getContentPane().setLayout(dialogoLayout);
        dialogoLayout.setHorizontalGroup(
            dialogoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        dialogoLayout.setVerticalGroup(
            dialogoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        jLabel1.setText("Apellido:");

        apellido.setToolTipText("Campo obligatorio con una longitud máxima de 50 caracteres.");
        apellido.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                apellidoKey(evt);
            }
        });

        nombres.setToolTipText("Campo obligatorio con una longitud máxima de 50 caracteres.");
        nombres.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                nombresKey(evt);
            }
        });

        jLabel2.setText("Nombres:");

        crear.setText("Crear");
        crear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                crear(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(apellido, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nombres, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(269, Short.MAX_VALUE)
                .addComponent(crear)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(apellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addComponent(crear)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void crear(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_crear
        try {
            this.limpiar();
            String ape= apellido.getText().trim();
            String nom= nombres.getText().trim();
            Verificador.verificarCliente(ape, nom);
            retorno= new Cliente(new ArrayList<Long>());
            retorno.setApellido(ape);
            retorno.setNombres(nom);
            dialogo.setVisible(false);
        } catch (VerificadorException ex) {this.marcarErrores(ex.obtenerErrores());}
    }//GEN-LAST:event_crear

    private void apellidoKey(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_apellidoKey
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
            this.crear(null);
    }//GEN-LAST:event_apellidoKey

    private void nombresKey(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nombresKey
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
            this.crear(null);
    }//GEN-LAST:event_nombresKey

    /**
     * @return un cliente o null si el dialogo es cancelado.
     */
    public Cliente hacerVisible(Component c)
    {
        dialogo.getContentPane().add(this, BorderLayout.CENTER);
        dialogo.pack();
        dialogo.setLocationRelativeTo(c);
        dialogo.setVisible(true);
        dialogo.dispose();
        return retorno;
    }
    
    private void limpiar()
    {
        apellido.setBackground(Color.white);
        nombres.setBackground(Color.white);
    }
    
    private void marcarErrores(List<Integer> errores)
    {
        String msj= "Se detectaron campos incorrectos.\n\nPara conocer el formato correcto, posicione el mouse\n" +
                "por un instante sobre el campo deseado.";
        for (int i : errores)
        {
            switch (i)
            {
                case Verificador.ERROR_CLIENTE_APELLIDO: apellido.setBackground(Color.red); break;
                case Verificador.ERROR_CLIENTE_NOMBRE: nombres.setBackground(Color.red); break;
            }
        }
        JOptionPane.showMessageDialog(this, msj, "Error", JOptionPane.ERROR_MESSAGE);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField apellido;
    private javax.swing.JButton crear;
    private javax.swing.JDialog dialogo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField nombres;
    // End of variables declaration//GEN-END:variables
}
